package cn.yunyichina.provider.pay.pacity.service.impl;

import cn.yunyichina.provider.iface.entity.bo.PacityOrderQueryRequestBO;
import cn.yunyichina.provider.iface.entity.bo.PacityRefundOrderQueryRequestBO;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.dto.pacity.PacityOrderQueryRequestDTO;
import cn.yunyichina.provider.iface.entity.dto.pacity.PacityOrderQueryResponseDTO;
import cn.yunyichina.provider.iface.entity.dto.pacity.PacityRefundOrderQueryRequestDTO;
import cn.yunyichina.provider.iface.entity.dto.pacity.PacityRefundOrderQueryResponseDTO;
import cn.yunyichina.provider.pay.pacity.constant.PacityConstant;
import cn.yunyichina.provider.pay.pacity.constant.ResponseEnum;
import cn.yunyichina.provider.pay.pacity.service.BaseService;
import cn.yunyichina.provider.pay.pacity.service.PacityOrderService;
import cn.yunyichina.utils.commons.HttpContentType;
import cn.yunyichina.utils.commons.HttpUtil;
import cn.yunyichina.utils.dozer.Dozer;
import cn.yunyichina.utils.security.SignUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Lullaby on 2017/8/2
 */
@Service
public class PacityOrderServiceImpl extends BaseService implements PacityOrderService {

    private static final Logger logger = LoggerFactory.getLogger(PacityOrderServiceImpl.class);

    public ResCommon<PacityOrderQueryResponseDTO> queryPacityOrder(PacityOrderQueryRequestDTO requestDTO) {
        logger.info("PacityOrderServiceImpl.queryPacityOrder.requestDTO -> {}", JSON.toJSONString(requestDTO));

        try {
            PacityOrderQueryRequestBO requestBO = Dozer.convert(requestDTO, PacityOrderQueryRequestBO.class);
            Map<String, String> params = Dozer.convert(requestBO, Map.class);

            String signContent = SignUtil.pacitySignContent(params);
            logger.info("PacityOrderServiceImpl.queryPacityOrder.signContent -> {}", signContent);
            String sign = SignUtil.pacitySign(signContent, requestDTO.getPrivateKey());
            logger.info("PacityOrderServiceImpl.queryPacityOrder.sign -> {}", sign);

            String postContent = HttpUtil.buildFormUrlEncodedParams(params);
            String postRequest = buildPacityPostRequestContent(postContent, sign);
            logger.info("PacityRefundServiceImpl.doPacityRefund.postRequest -> {}", postRequest);

            String postResponse = HttpUtil.httpBasicPostWithKeyValue(
                    PacityConstant.PACITY_USER_HTTP_BASIC_AUTH_KEY,
                    requestDTO.getAccessToken(), postRequest,
                    getConfig(PacityConstant.PACITY_URL_TRADE_ORDERQUERY),
                    HttpContentType.FORMURLENCODED
            );
            logger.info("PacityOrderServiceImpl.queryPacityOrder.postResponse -> {}", postResponse);

            PacityOrderQueryResponseDTO responseDTO = JSON.parseObject(postResponse, PacityOrderQueryResponseDTO.class);
            logger.info("PacityOrderServiceImpl.queryPacityOrder.responseDTO -> {}", JSON.toJSONString(responseDTO));

            if (responseDTO.isResultCodeSuccess()) {
                if (!SignUtil.verifyPacitySign(JSON.parseObject(postResponse, Map.class), requestDTO.getPublicKey())) {
                    return new ResCommon<PacityOrderQueryResponseDTO>().buildResultCodeAndMessage(
                            ResponseEnum.PACITY_INVALID_SIGN.getCode(),
                            ResponseEnum.PACITY_INVALID_SIGN.getMessage()
                    );
                }
            }

            return new ResCommon<PacityOrderQueryResponseDTO>().buildResult(responseDTO);
        } catch (Exception e) {
            logger.error("PacityOrderServiceImpl.queryPacityOrder.Exception", e);

            return new ResCommon<PacityOrderQueryResponseDTO>().buildResultCodeAndMessage(
                    ResponseEnum.PACITY_PAY_EXCEPTION.getCode(),
                    ResponseEnum.PACITY_PAY_EXCEPTION.getMessage()
            );
        }
    }

    public ResCommon<PacityRefundOrderQueryResponseDTO> queryPacityRefundOrder(PacityRefundOrderQueryRequestDTO requestDTO) {
        logger.info("PacityOrderServiceImpl.queryPacityRefundOrder.requestDTO -> {}", JSON.toJSONString(requestDTO));

        try {
            PacityRefundOrderQueryRequestBO requestBO = Dozer.convert(requestDTO, PacityRefundOrderQueryRequestBO.class);
            Map<String, String> params = Dozer.convert(requestBO, Map.class);

            String signContent = SignUtil.pacitySignContent(params);
            logger.info("PacityOrderServiceImpl.queryPacityRefundOrder.signContent -> {}", signContent);
            String sign = SignUtil.pacitySign(signContent, requestDTO.getPrivateKey());
            logger.info("PacityOrderServiceImpl.queryPacityRefundOrder.sign -> {}", sign);

            String postContent = HttpUtil.buildFormUrlEncodedParams(params);
            String postRequest = buildPacityPostRequestContent(postContent, sign);
            logger.info("PacityOrderServiceImpl.queryPacityRefundOrder.postRequest -> {}", postRequest);

            String postResponse = HttpUtil.httpBasicPostWithKeyValue(
                    PacityConstant.PACITY_USER_HTTP_BASIC_AUTH_KEY,
                    requestDTO.getAccessToken(), postRequest,
                    getConfig(PacityConstant.PACITY_URL_PAY_REFUNDQUERY),
                    HttpContentType.FORMURLENCODED
            );
            logger.info("PacityOrderServiceImpl.queryPacityRefundOrder.postResponse -> {}", postResponse);

            PacityRefundOrderQueryResponseDTO responseDTO = JSON.parseObject(postResponse, PacityRefundOrderQueryResponseDTO.class);
            logger.info("PacityOrderServiceImpl.queryPacityRefundOrder.responseDTO -> {}", JSON.toJSONString(responseDTO));

            if (responseDTO.isResultCodeSuccess()) {
                if (!SignUtil.verifyPacitySign(JSON.parseObject(postResponse, Map.class), requestDTO.getPublicKey())) {
                    return new ResCommon<PacityRefundOrderQueryResponseDTO>().buildResultCodeAndMessage(
                            ResponseEnum.PACITY_INVALID_SIGN.getCode(),
                            ResponseEnum.PACITY_INVALID_SIGN.getMessage()
                    );
                }
            }

            return new ResCommon<PacityRefundOrderQueryResponseDTO>().buildResult(responseDTO);
        } catch (Exception e) {
            logger.error("PacityOrderServiceImpl.queryPacityRefundOrder.Exception", e);

            return new ResCommon<PacityRefundOrderQueryResponseDTO>().buildResultCodeAndMessage(
                    ResponseEnum.PACITY_PAY_EXCEPTION.getCode(),
                    ResponseEnum.PACITY_PAY_EXCEPTION.getMessage()
            );
        }
    }

}
